<template>
  <div>
    <!-- 搜索框 -->
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="">
          <el-input v-model="searchInfo.directoryName" placeholder="请输入目录体系名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮列表 -->
    <div class="gva-btn-list">
      <el-button type="primary" icon="plus" @click="openDialog('新增', null)">新增</el-button>
<!--      <el-button icon="delete" type="primary" link @click="onDelete(scope.row)">删除</el-button>-->
      <el-button icon="refresh" @click="onFresh">刷新缓存</el-button>
      <ExportExcel template-id="" :limit="9999" />
      <ImportExcel template-id="" @on-success="getTableData" />
    </div>

    <!-- 表格 -->
    <div class="gva-table-box">
      <el-table :data="filteredTableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="序号" min-width="60" type="index"/>
        <el-table-column align="left" label="目录名称" min-width="150" prop="DirectoryName" />
        <el-table-column align="left" label="上级目录" min-width="150" prop="ParentId" >
          <template #default="scope">
            {{getParentDirName(scope.row.ParentId)}}
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建时间" min-width="200" prop="CreatedAt" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="更新时间" min-width="200" prop="UpdatedAt" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.UpdatedAt) }}
          </template>
        </el-table-column>

        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button icon="edit" type="primary" link @click="openDialog('编辑', scope.row)">编辑</el-button>
            <el-button icon="delete" type="primary" link @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 对话框 -->
    <el-drawer v-model="dialogFormVisible" size="60%" :before-close="closeDialog" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="enterDialog">确定</el-button>
          </div>
        </div>
      </template>

      <warning-bar title="新增/编辑信息" />
      <el-form ref="apiForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="目录名称" prop="DirectoryName">
          <el-input v-model="form.DirectoryName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="上级目录" prop="ParentId">
          <el-select v-model="form.ParentId" placeholder="请选择上级目录">
            <el-option
                label="顶级目录"
                value="0"
            />
            <el-option
                v-for="directory in existingDirectories"
                :key="directory.DirectoryId"
                :label="directory.DirectoryName"
                :value="directory.DirectoryId"
            />
          </el-select>
        </el-form-item>


      </el-form>

    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { getDataDirectoryList, addDataDirectory, updateDataDirectory, deleteDataDirectory } from '@/api/information'

// 表格数据
const originalTableData = ref([])
const searchInfo = reactive({ directoryName: '' })
const apis = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const existingDirectories = ref([]);
const dialogFormVisible = ref(false)
const dialogTitle = ref('')
const form = reactive({
  DirectoryId: '',
  DirectoryName: '',
  ParentId: '',
  CreatedAt: '',
  UpdatedAt:'',
})

const rules = ref({
  DirectoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }],
  ParentId: [{ required: true, message: '请输入上级目录', trigger: 'blur' }],
})

// 过滤后的表格数据
const filteredTableData = computed(() => {
  const searchTerm = searchInfo.directoryName.toLowerCase()
  return originalTableData.value.filter(item =>
      item.DirectoryName.toLowerCase().includes(searchTerm)
  )
})

const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


const onSubmit = () => {
  getTableData()
}

const onReset = () => {
  searchInfo.directoryName = ''
  getTableData()
}

const openDialog = (title, row) => {
  dialogTitle.value = title === '新增' ? '新增 信息' : '编辑 信息'
  if (row) {
    form.DirectoryId = row.DirectoryId
    form.DirectoryName = row.DirectoryName
    form.ParentId = row.ParentId
    form.CreatedAt = row.CreatedAt
    form.UpdatedAt = row.UpdatedAt

  } else {
    form.DirectoryId = ''
    form.DirectoryName = ''
    form.ParentId = ''
    form.CreatedAt = ''
    form.UpdatedAt = ''
  }
  dialogFormVisible.value = true
}

const closeDialog = () => {
  dialogFormVisible.value = false
}



const enterDialog = async () => {
  try {
    if (dialogTitle.value === '新增 信息') {
      await addDataDirectory({
        directoryName: form.DirectoryName,
        parentId: form.ParentId || '0'
      });
    } else if (dialogTitle.value === '编辑 信息') {
      await updateDataDirectory({
        directoryId: form.DirectoryId,
        directoryName: form.DirectoryName,
        parentId: form.ParentId || '0'
      });
    }
    ElMessage({
      type: 'success',
      message: '操作成功'
    });
    closeDialog();
    getTableData();
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '操作失败'
    });
  }
}

const onDelete = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDataDirectory({ directoryId: row.DirectoryId })
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      getTableData()
    } catch (error) {
      ElMessage({
        type: 'error',
        message: '删除失败'
      })
    }
  }).catch(() => {
    console.log('取消删除')
  })
}



const onFresh = () => {
  ElMessageBox.confirm('确定要刷新缓存吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '刷新缓存成功'
    })
    // 刷新缓存按钮逻辑
  }).catch(() => {
    console.log('取消刷新')
  })
}

const handleSelectionChange = (val) => {
  apis.value = val
  console.log('选择变化', val)
}

// 获取表格数据的同时，获取现有目录列表
const getTableData = async () => {
  try {
    const response = await getDataDirectoryList(page.value, pageSize.value);
    console.log('API Response:', response.data);

    // 更新表格数据
    originalTableData.value = response.data.list.map(item => ({
      DirectoryId: item.DirectoryId,
      DirectoryName: item.DirectoryName || '',
      ParentId: item.ParentId || '',
      CreatedAt: item.CreatedAt || '',
      UpdatedAt: item.UpdatedAt || '',
    }));

    // 更新现有目录列表
    existingDirectories.value = response.data.list;

    total.value = response.data.total;
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '获取数据失败'
    });
  }
}

const getParentDirName = (val) => {
  if (val === "0") {
    return "顶级目录";
  }
  const name =existingDirectories.value.find(dir => dir.DirectoryId === val)?.DirectoryName || ' ';
  return name
};

const handleCurrentChange = (newPage) => {
  page.value = newPage
  getTableData()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  getTableData()
}

// 初始化数据
getTableData()
</script>

<style scoped>
</style>
